package com.example.exchangeapp.zjs;

import static android.content.ContentValues.TAG;
import static com.example.exchangeapp.yy.constant.AppId.AppId;
import static com.example.exchangeapp.yy.constant.AppSecret.appSecret;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.exchangeapp.MainActivity;
import com.example.exchangeapp.R;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class login extends AppCompatActivity implements View.OnClickListener{

    private EditText etUserAccount;
    private EditText etUserPassword;
    String userAccount;
    String userPassword;
    private final Gson gson = new Gson();
    private User user;
    private View rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etUserAccount=findViewById(R.id.etUsername);
        etUserPassword=findViewById(R.id.etPassword);
        rootView = findViewById(R.id.root_view);
        //Button btSendCode = findViewById(R.id.btnSendCode);
        //btSendCode.setOnClickListener(this);
        Button btLogin = findViewById(R.id.btnLogin);
        btLogin.setOnClickListener(this);

        TextView tvRegister = findViewById(R.id.tvRegister);
        // 添加下划线样式
        tvRegister.setPaintFlags(tvRegister.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        //重写注册按钮监听事件
        tvRegister.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(login.this, register.class);
                startActivity(intent);
            }
        });

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // 显示注册成功的提示信息
            String loginMessage = extras.getString("register_message");
            Toast.makeText(this, loginMessage, Toast.LENGTH_SHORT).show();
        }
    }

    //用户登录
    private void postUser(){
        new Thread(() -> {

//            userPhoneNumber=etPhoneNumber.getText().toString();
//            System.out.println("电话号码为"+userPhoneNumber);
//            userCodeService=etCodeService.getText().toString();
//            System.out.println("验证码为"+userCodeService);
            userAccount=etUserAccount.getText().toString();
            userPassword=etUserPassword.getText().toString();
            // 请求的url路径
            String url = "http://47.107.52.7:88/member/tran/user/login";

            //我的f9ed7014c8cb45169ab4cc0728775790和26073a2f31b8baca64eca93c3c2c5a3dd2313
            //yy的ea0f4556cf414613a551ca2c25840189和139172f805f8d3e654ffb891d963d96f64f62
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", AppId)
                    .add("appSecret", appSecret)
                    .add("Content-Type", "application/json")
                    .build();

            // 请求体
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("password", userPassword);
            bodyMap.put("username", userAccount);
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callbackLogin);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callbackLogin = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            showSnackbar("连接服务器失败");

            Log.e(TAG, "连接服务器失败!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", body);
            // 解析json串到自己封装的状态
            BaseResponse dataResponseBody = gson.fromJson(body, BaseResponse.class);
            Log.d("个人信息为", dataResponseBody.toString());
            if (dataResponseBody.getCode() == 200) {
                user = dataResponseBody.getData();

                //获取可写数据库
                MySQLiteOpenHelper mySQLiteHelper = new MySQLiteOpenHelper(login.this);
                SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();

                //创建ContentValues以Key-Value的形式封装数据
                ContentValues values = new ContentValues();
                values.put("ID", user.getId());
                values.put("phoneNumber", user.getPhoneNumber());
                values.put("money", user.getMoney());
                values.put("avatar", user.getAvatar());
                System.out.println("用户数据为"+values.toString());

                //执行insert方法，插入数据
                long newRowId = db.insert("Users", null, values);
                System.out.println("插入结果为"+newRowId);

                Intent intent=new Intent(login.this, MainActivity.class);
                intent.putExtra("login_message", "登录成功");
                intent.putExtra("login_code", "200");
                startActivity(intent);

            }else {
                showSnackbar("登录失败，请检查用户名和密码是否正确");
            }
        }
    };


    //发送验证码
//    private void getCode(){
//        new Thread(() -> {
//            userPhoneNumber=etPhoneNumber.getText().toString();
//            System.out.println("电话号码为"+userPhoneNumber);
//            // 请求的url路径
//            String url = "http://47.107.52.7:88/member/tran/user/send?phone="+userPhoneNumber;
//
//            // 请求头
//            Headers headers = new Headers.Builder()
//                    .add("Accept", "application/json, text/plain, */*")
//                    .add("appId", "7050ff6db19341b482e0856a203e9160")
//                    .add("appSecret", "70724ea34f7f73f1e46c48e63f3dfd9183bd1")
//                    .build();
//
//            //请求组合创建
//            Request request = new Request.Builder()
//                    .url(url)
//                    // 将请求头加至请求中
//                    .headers(headers)
//                    .get()
//                    .build();
//            try {
//                OkHttpClient client = new OkHttpClient();
//                //发起请求，传入callback进行回调
//                client.newCall(request).enqueue(callbackCode);
//            }catch (NetworkOnMainThreadException ex){
//                ex.printStackTrace();
//            }
//        }).start();
//    }

    private final Callback callbackCode = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            showSnackbar("连接服务器失败");

            Log.e(TAG, "Failed to connect server!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", body);
            // 解析json串到自己封装的状态
            CodeSevice dataCodeSevice = gson.fromJson(body,CodeSevice.class);
            Log.d("信息为", "信息为"+dataCodeSevice.toString());
            if (dataCodeSevice.getCode() == 200) {
                showSnackbar("发送验证码成功，请注意查收");
            }else {
                showSnackbar("发送验证码失败");
            }
        }
    };
//    private void getCode(){
//        new Thread(() -> {
//
//            userPhoneNumber=etPhoneNumber.getText().toString();
//            System.out.println("电话号码为"+userPhoneNumber);
//            // 请求的url路径
//            String url = "http://47.107.52.7:88/member/tran/user/send?phone="+userPhoneNumber;
//
//            // 请求头
//            Headers headers = new Headers.Builder()
//                    .add("Accept", "application/json, text/plain, */*")
//                    .add("appId", "7050ff6db19341b482e0856a203e9160")
//                    .add("appSecret", "70724ea34f7f73f1e46c48e63f3dfd9183bd1")
//                    .build();
//
//            //请求组合创建
//            Request request = new Request.Builder()
//                    .url(url)
//                    // 将请求头加至请求中
//                    .headers(headers)
//                    .get()
//                    .build();
//            try {
//                OkHttpClient client = new OkHttpClient();
//                //发起请求，传入callback进行回调
//                client.newCall(request).enqueue(callbackCode);
//            }catch (NetworkOnMainThreadException ex){
//                ex.printStackTrace();
//            }
//        }).start();
//    }
//
//    private final Callback callbackCode = new Callback() {
//        @Override
//        public void onFailure(Call call, IOException e) {
//            showSnackbar("连接服务器失败");
//
//            Log.e(TAG, "Failed to connect server!");
//            e.printStackTrace();
//        }
//
//        @Override
//        public void onResponse(Call call, Response response) throws IOException {
//            // 获取响应体的json串
//            String body = response.body().string();
//            Log.d("json串为", body);
//            // 解析json串到自己封装的状态
//            CodeSevice dataCodeSevice = gson.fromJson(body,CodeSevice.class);
//            Log.d("信息为", "信息为"+dataCodeSevice.toString());
//            if (dataCodeSevice.getCode() == 200) {
//                showSnackbar("发送验证码成功，请注意查收");
//            }else {
//                showSnackbar("发送验证码失败");
//            }
//        }
//    };

    private void showSnackbar(String message) {
        Snackbar snackbar = Snackbar.make(rootView, message, Snackbar.LENGTH_SHORT);
        snackbar.getView().setBackgroundResource(R.color.snackbar_background_color);
        snackbar.setTextColor(getResources().getColor(android.R.color.white));
        snackbar.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //case R.id.btnSendCode:
                //getCode();
                //break;
            case R.id.btnLogin:
                postUser();
                break;
        }
    }
}